package com.youbug.mall.order_oms.listener;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.rabbitmq.client.Channel;
import com.youbug.common.config.AlipayTemplate;
import com.youbug.mall.order_oms.entity.OmsOrder;
import com.youbug.mall.order_oms.service.IOmsOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {

    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private IOmsOrderService orderService;

    @RabbitHandler
    public void listener(OmsOrder order, Channel channel, Message message) throws IOException {
        System.out.println("收到过期的订单信息：准备关闭订单"+order.getOrderSn());
        try{
            orderService.closeOrder(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            alipayTemplate.closePay(order.getOrderSn());
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
